# -*- coding: utf-8 -*-


from aeConn import dbHandle

import yaml
import hashlib

def addUserToDB(username, password, email, name, institution):

	hashPass = hashlib.md5(password)

	data = {'username':username, 'password':hashPass.hexdigest(), 'email':email, 'name':name, 'institution':institution}

	body = yaml.dump(data)

	dbHandle.postAction("insert", body, {'type':'User'})


def login(host, username, password):
	dbHandle.connect(host)

	if not username and not password:
		return
	elif not host or not username or not password:
		raise ValueError

	hashPass = hashlib.md5(password)

	body = yaml.dump({'password':hashPass.hexdigest()})

	yml = dbHandle.postAction("login", body, {'username':username})

	resp = yaml.load(yml)

	dbHandle.setSID(resp['currentSID'])


def logout():
	dbHandle.getAction("logout", {})
	dbHandle.setSID('')


def changePass(oldPass, newPass):

	hash1 = hashlib.md5(oldPass)
	hash2 = hashlib.md5(newPass)

	body = yaml.dump({'oldPassword':hash1.hexdigest(), 'newPassword':hash2.hexdigest()})

	dbHandle.postAction('changePassword', body, {})


def userLoggedIn():
	return dbHandle.userLoggedIn()